import React from 'react';
import {
  Button, Icon, Input, Form, message,
} from 'antd';
import { createProcess } from 'services/process';
import BpmnEditor from 'components/bpmnEditor/BpmnEditor';
import BPMN from 'assets/BpmnXML.bpmn';


export default class ProcessDesign extends React.Component {
  componentDidMount() {
    const { bpmnEditor } = this;
    bpmnEditor.init(BPMN);
  }

  uploadBPMN = () => {
    const { inputRef } = this;
    if (!inputRef.input.value) {
      message.error('请输入流程名称!');
      return;
    }
    const { load, saveXML } = this.bpmnEditor;
    saveXML((err, xml) => {
      if (err) {
        console.error('could not save BPMN 2.0 diagram', err);
      }
      const file = new File([xml], inputRef.input.value, {
        type: 'text/plain',
      });
      const formData = new FormData();
      formData.append('name', inputRef.input.value);
      formData.append('file', file);
      createProcess(formData).then(() => {
        message.success('上传成功');
        load(BPMN);
        inputRef.input.value = '';
      }, (reason) => {
        console.error(reason);
      });
    });
  }

  render() {
    return (
      <>
        <BpmnEditor ref={(editor) => { this.bpmnEditor = editor; }} />
        <Form layout="inline">
          <Form.Item>
            <Input
              ref={(input) => { this.inputRef = input; }}
              prefix={<Icon type="file" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="流程名称"
            />
          </Form.Item>
          <Form.Item>
            <Button type="default" htmlType="submit" onClick={this.uploadBPMN}>
              创建流程
            </Button>
          </Form.Item>
        </Form>
      </>
    );
  }
}
